import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { isArray } from 'class-validator';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp(); // 获取请求上下文
    const response = ctx.getResponse(); // 获取请求上下文中的 response对象
    const status = exception.getStatus(); // 获取异常状态码
    let rspObj;
    switch (status) {
      case HttpStatus.NOT_FOUND:
        rspObj = '接口不存在 ';
        break;
      // 这个错误状态 只针对 class-validator的IsNotEmpty
      case HttpStatus.BAD_REQUEST:
        let message = (exception.getResponse() as any).message;
        if (isArray(message)) {
          message = message.join();
        }
        rspObj = message;
        break;
      default:
        rspObj = exception.getResponse();
        break;
    }

    const errorResponse = {
      data: null,
      message: rspObj,
      code: status,
      timeStamp: new Date().getTime(),
    };

    response.status(HttpStatus.OK);
    response.header('Content-Type', 'application/json; charset=utf-8');
    response.send(errorResponse);
  }
}
